package Blocking;

public class MyBlockingQueue {
    private Integer[] elem;
    //有效数据长度
    private int size = 0;
    //头节点，尾节点
    private int head = 0;
    private int tail = 0;
    public MyBlockingQueue(int capacity) {
        if(capacity <= 0) {
            throw new RuntimeException("队列长度必须大于0！！");
        }
        elem = new Integer[capacity];
    }
    public void put(Integer value) throws InterruptedException {
        synchronized (this) {
            while(size >= elem.length) {
                this.wait();
            }
            //尾插
            elem[tail] = value;
            tail++;
            //处理tail越界问题
            if(tail >= elem.length) {
                tail = 0;
            }
            size++;
            this.notifyAll();
        }
    }
    public synchronized Integer take() throws InterruptedException {
        while(size == 0) {
            this.wait();
        }
        Integer value = elem[head];
        head++;
        if(head >= elem.length) {
            head = 0;
        }
        size--;
        synchronized (this) {
            this.notifyAll();
        }
        return value;
    }
}
